//
//  SourceDetailViewController.swift
//  clreader
//
//  Created by colin on 2019/3/27.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit
import MobilePlayer
import AVKit

class SourceDetailViewController: CLBaseViewController {

    private var sourceType = SourceType.精讲
    private var goods_id = 0
    private var goodsInfo = JSONObject() {
        didSet {
            self.refresh()
            // 是否收藏
            if let collect = self.goodsInfo["collect"] as? Int,collect > 0 {
                self.isCollect = true
            } else {
                self.isCollect = false
            }
        }
    }
    private var isCollect = false {
        didSet {
            if self.isCollect {
                self.buttonLike.setImage(UIImage(named: "button_like_checked"), for: .normal)
            } else {
                self.buttonLike.setImage(UIImage(named: "button_like_normal"), for: .normal)
            }
        }
    }
    
    private lazy var topBar = CLNavigationBar()
    private lazy var buttonLike = UIButton(type: .custom) // 喜欢按钮

    private var bottomBar:UIView?
    private var contentView:SourceDetailContainerView?
    
    convenience init(sourceType:SourceType, goods_id:Int) {
        self.init()
        self.sourceType = sourceType
        self.goods_id = goods_id
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        //topBar
        self.topBar.do {
            $0.title = ""
            $0.backHandle = { [weak self] in
                self?.navigationController?.popViewController(animated: true)
            }
            
            let buttonShare = UIButton(type: .custom).then {
                $0.setImage(UIImage(named: "button_share"), for: .normal)
            }
            let itemShare = CLNavigationBar.Item(customView: buttonShare, viewHandle: {
                print("分享")
            })
            
            self.buttonLike.setImage(UIImage(named: "button_like_normal"), for: .normal)
            let itemLike = CLNavigationBar.Item(customView: self.buttonLike, viewHandle: { [weak self] in
                
                guard let `self` = self else { return }
                
                // 判断是否已经登录
                if !AccountManager.shared.isLogin {
                    let loginController = LoginViewController()
                    let navController = CLNavigationController(rootViewController: loginController)
                    self.present(navController, animated: true, completion: nil)
                    return
                }
                
                let token = AccountManager.shared.token
                if !self.isCollect {
                    self.hud.showProgress()
                    _ = Router.addCollect(goods_id: self.goods_id, token: token).request({ (response:RequestResponse<JSONObject>) in
                        
                        self.hud.hide()
                        
                        if case .success = response {
                            self.isCollect = true
                        }
                        
                        if case .failure(_, let message) = response {
                            self.hud.showText(message)
                        }
                        
                    })
                } else {
                    self.hud.showProgress()
                    _ = Router.removeCollect(goods_id: self.goods_id, token: token).request({ (response:RequestResponse<JSONObject>) in
                        
                        self.hud.hide()
                        
                        if case .success = response {
                            self.isCollect = false
                        }
                        
                        if case .failure(_, let message) = response {
                            self.hud.showText(message)
                        }
                        
                    })
                }
                
            })
            
            $0.rightItems = [itemLike, itemShare]
        }
        self.topBar.show(inView: self.view)
        
        // 加载数据
        self.loadGoodInfo()
    }

}

extension SourceDetailViewController {
    
    private func refresh() {
        
        self.contentView?.removeFromSuperview()
        self.bottomBar?.removeFromSuperview()
        
        // 纸书购买链接
        var buy_url = ""
        if let value = self.goodsInfo["buy_url"] as? String, !value.isEmpty {
            buy_url = value
        }
        
        // 是否免费
        var is_free = false
        if let value = self.goodsInfo["is_free"] as? Int, value == 1 {
            is_free = true
        }
        
        // 是否已经购买
        var is_buy = false
        if let value = self.goodsInfo["is_buy"] as? Int, value == 1 {
            is_buy = true
        }
        
        // 价格
        var price = 0.0
        if let value = self.goodsInfo["price"] as? Double {
            price = value
        }
        
        if self.sourceType == .视频 {
            let bottomBar_ = UIView().then {
                $0.backgroundColor = UIColor.white
            }
            
            let buttonPlay_ = UIButton(type: .custom).then {
                $0.setTitle("播放", for: .normal)
                $0.setTitleColor(UIColor.white, for: .normal)
                $0.backgroundColor = UIColor(hex: "AE1600")
                $0.addTarget(self, action: #selector(self.actionPlay(_:)), for: .touchUpInside)
            }
            
            bottomBar_.addSubview(buttonPlay_)
            buttonPlay_.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            self.view.addSubview(bottomBar_)
            bottomBar_.snp.makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.height.equalTo(50.0)
                make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
            }
            
            self.bottomBar = bottomBar_
            
        } else if !buy_url.isEmpty || (!is_free && !is_buy) {
            
            let bottomBar_ = UIView().then {
                $0.backgroundColor = UIColor.white
            }
            
            var buttons = [UIButton]()
            
            // 试读or阅读
            if self.sourceType == .电子书 {
                let buttonRead_ = UIButton(type: .custom).then {
                    
                    if !is_free && !is_buy {
                        $0.setTitle("试读", for: .normal)
                    } else {
                        $0.setTitle("阅读", for: .normal)
                    }
                    
                    $0.addTarget(self, action: #selector(self.actionRead(_:)), for: .touchUpInside)
                }
                buttons.append(buttonRead_)
            }
            
            // 购买纸质书
            if !buy_url.isEmpty {
                let buttonBuyPaper_ = UIButton(type: .custom).then {
                    $0.setTitle("纸书购买", for: .normal)
                    $0.addTarget(self, action: #selector(self.actionBuyPaper(_:)), for: .touchUpInside)
                }
                buttons.append(buttonBuyPaper_)
            }
            
            // 购买
            if !is_free && !is_buy {
                let buttonBuy_ = UIButton(type: .custom).then {
                    $0.setTitle("购买 \(price)", for: .normal)
                    $0.addTarget(self, action: #selector(self.actionBuy(_:)), for: .touchUpInside)
                }
                buttons.append(buttonBuy_)
            }
            
            // 添加按钮
            var pre:UIButton?
            for index in 0 ..< buttons.count {
                let button = buttons[index]
                bottomBar_.addSubview(button)
                button.snp.makeConstraints { (make) in
                    if let pre_ = pre {
                        make.left.equalTo(pre_.snp.right)
                        make.width.equalTo(pre_.snp.width)
                    } else {
                        make.left.equalToSuperview()
                    }
                    
                    if index == buttons.count - 1 {
                        make.right.equalToSuperview()
                    }
                    
                    make.top.bottom.equalToSuperview()
                }
                pre = button
            }
            
            // 按钮样式
            if buttons.count == 1 {
                let button = buttons[0]
                button.setTitleColor(UIColor.white, for: .normal)
                button.backgroundColor = UIColor(hex: "AE1600")
            }
            
            if buttons.count == 2 {
                let button1 = buttons[0]
                button1.setTitleColor(UIColor.black, for: .normal)
                button1.backgroundColor = UIColor.white
                
                let button2 = buttons[1]
                button2.setTitleColor(UIColor.white, for: .normal)
                button2.backgroundColor = UIColor(hex: "AE1600")
            }
            
            if buttons.count == 3 {
                let button1 = buttons[0]
                button1.setTitleColor(UIColor.black, for: .normal)
                button1.backgroundColor = UIColor.white
                
                let button2 = buttons[1]
                button2.setTitleColor(UIColor.white, for: .normal)
                button2.backgroundColor = UIColor(hex: "00ff00")
                
                let button3 = buttons[2]
                button3.setTitleColor(UIColor.white, for: .normal)
                button3.backgroundColor = UIColor(hex: "AE1600")
            }

            self.view.addSubview(bottomBar_)
            bottomBar_.snp.makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.height.equalTo(50.0)
                make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
            }
            
            self.bottomBar = bottomBar_
        }
        
        // 头部
        let headerView = SourceDetailHeaderView(sourceType: self.sourceType, data: self.goodsInfo)
        
        var controllers = [ScrollViewController]()
        
        // 目录，打包资源才有目录
        switch self.sourceType {
        case .专题:
            let controller = SourceSubViewController(data: self.goodsInfo, headerHeight: headerView.viewHeight)
            controllers.append(controller)
        case .精讲, .有声书:
            let controller = SourceCatogryViewController(data: self.goodsInfo, headerHeight: headerView.viewHeight)
            controllers.append(controller)
        default:break
        }
        
        // 详情
        let introController = SourceIntroViewController(data: self.goodsInfo, headerHeight: headerView.viewHeight)
        controllers.append(introController)
        
        let container = SourceDetailContainerView(parentController: self, headerView: headerView, controllers: controllers)
        self.view.insertSubview(container, at: 0)
        container.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(self.topBar.snp.bottom)
            
            if let bottomBar_ = bottomBar {
                make.bottom.equalTo(bottomBar_.snp.top)
            } else {
                make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
            }
            
        }
        self.contentView = container
    }
    
    private func loadGoodInfo() {
        self.hud.showProgress()
        
        let token = AccountManager.shared.token
        
        _ = Router.goods_info(goods_id: self.goods_id, token: token).request { [weak self] (response:RequestResponse<JSONObject>) in
            
            self?.hud.hide()
            
            if case .success(let successData,_) = response {
                if let goodsInfo_ = successData {
                    self?.goodsInfo = goodsInfo_
                }
            }
            
            if case .failure(_,let message) = response {
                self?.hud.showText(message)
            }
        }
    }
    
    // MARK - 试读or阅读
    @objc private func actionRead(_ sender:Any) {
    }
    
    // MARK - 播放
    @objc private func actionPlay(_ sender:Any) {
        if self.sourceType == .音频 {
            // 暂时跳转播放音频
            let controller = AudioPlayViewController()
            self.show(controller, sender: nil)
            controller.play(audios: CLAudio.audios(objects: [self.goodsInfo]))
        } else if self.sourceType == .视频 {
            if let goods_url = self.goodsInfo["goods_url"] as? String, !goods_url.isEmpty,
                let baseUrl = URL(string: Router.baseUrl) {
                let videoUrl = baseUrl.appendingPathComponent(goods_url)
                
                let controller = MobilePlayerViewController(contentURL: videoUrl)
                controller.title = self.goodsInfo["title"] as? String
                controller.activityItems = [videoUrl] // Check the documentation for more information.
                self.present(controller, animated: true, completion: nil)
            }
        }
    }
    
    // MARK - 纸书购买
    @objc private func actionBuyPaper(_ sender:Any) {
        let buyUrl = self.goodsInfo["buy_url"] as? String
        let controller = CLWebViewController(urlString: buyUrl)
        self.show(controller, sender: nil)
    }
    
    @objc private func actionBuy(_ sender:Any) {
        self.hud.showText("购买")
    }
    
}
